package com.jsjosem.aftersales.ui.notifications;

import static com.jsjosem.aftersales.utils.CommonUtils.selectPhoto;
import static com.jsjosem.aftersales.utils.CommonUtils.showBigImg;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.jsjosem.aftersales.R;
import com.jsjosem.aftersales.adapter.ImgListViewAdapter;
import com.jsjosem.aftersales.api.EventApi;
import com.jsjosem.aftersales.api.RetrofitClient;
import com.jsjosem.aftersales.component.CustomGridView;
import com.jsjosem.aftersales.constant.Command;
import com.jsjosem.aftersales.data.request.EventReceiptRequest;
import com.jsjosem.aftersales.data.response.BaseResponse;
import com.jsjosem.aftersales.listener.ListenerManager;
import com.jsjosem.aftersales.request.AsyncRequest;
import com.jsjosem.aftersales.request.FileRequest;
import com.jsjosem.aftersales.utils.PermissionUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.wang.avi.AVLoadingIndicatorView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Retrofit;

public class CreateEventReceiptActivity extends AppCompatActivity {

    private ImageView ivAddImg;

    private final List<String> urls = new ArrayList<>();

    private CustomGridView gridView;
    private ImgListViewAdapter imgListViewAdapter;
    private Button btSubmit;
    private String eventId;
    private EditText etReceiptDescription;
    private Dialog loadingDialog;
    private String description;
    private List<String> uploadImgUrls;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_event_receipt);
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        eventId = extras.get("eventId").toString();
        initView();
    }

    private void initImgView() {
        imgListViewAdapter = new ImgListViewAdapter(this, urls);
        gridView.setAdapter(imgListViewAdapter);
        gridView.setOnItemClickListener((adapterView, listView, position, id) -> {
            // 放大图片
            showBigImg(this, urls, position);
        });
    }

    private void initView() {
        ivAddImg = findViewById(R.id.iv_add_img);
        gridView = findViewById(R.id.img_grid_view);
        etReceiptDescription = findViewById(R.id.create_event_receipt_result);
        btSubmit = findViewById(R.id.bt_submit);
        ivAddImg.setOnClickListener(view -> selectPhoto(this));
        btSubmit.setOnClickListener(view -> {
            // 获取故障描述
            description = etReceiptDescription.getText().toString();
            uploadFile();
        });
        initImgView();
    }

    private void uploadFile() {
        uploadImgUrls = new ArrayList<>();
        if (urls.size() == 0) {
            Toast.makeText(this, "请添加现场照片", Toast.LENGTH_SHORT).show();
        } else {
            loadingShow();
            for (int i = 0; i < urls.size(); i++) {
                File file = new File(urls.get(i));
                FileRequest request = new FileRequest();
                int index = i;
                request.uploadFile(file, res -> {
                    uploadImgUrls.add(res.getData().getPath());
                    if (index == urls.size() - 1) {
                        Retrofit retrofit = RetrofitClient.getInstance();
                        EventApi eventApi = retrofit.create(EventApi.class);
                        EventReceiptRequest eventReceiptRequest = new EventReceiptRequest();
                        eventReceiptRequest.setDescription(description);
                        eventReceiptRequest.setImages(uploadImgUrls);
                        Call<BaseResponse<Void>> receiptCall = eventApi.receipt(eventId, eventReceiptRequest);
                        AsyncRequest<BaseResponse<Void>> asyncRequest = new AsyncRequest<>();
                        asyncRequest.sendRequest(receiptCall, receiptRes -> {
                            // 回执提交成功，通知事件详情页更新数据
                            ListenerManager.getInstance().sendBroadCast(Command.NOTIFY_REFRESH_EVENT_INFO_DATA, null, null);
                            // 关闭当前activity
                            finish();
                            loadingDialog.dismiss();
                        }, errMsg -> {
                            loadingDialog.dismiss();
                            Toast.makeText(this, errMsg.toString(), Toast.LENGTH_SHORT).show();
                        });
                    }
                }, failedMessage -> {
                    loadingDialog.dismiss();
                    Toast.makeText(this, failedMessage.toString(), Toast.LENGTH_SHORT).show();
                });
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PictureConfig.CHOOSE_REQUEST && resultCode == RESULT_OK && null != data) {
            List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
            for (LocalMedia localMedia : selectList) {
                urls.add(localMedia.getPath());
            }
            imgListViewAdapter.notifyDataSetChanged();
            ivAddImg.setVisibility(View.VISIBLE);
        }
        if (requestCode == PictureConfig.REQUEST_CAMERA && resultCode == RESULT_OK && null != data) {
            List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
            for (LocalMedia localMedia : selectList) {
                urls.add(localMedia.getPath());
            }
            imgListViewAdapter.notifyDataSetChanged();
            ivAddImg.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (PermissionUtils.isPermissionGranted(this)) {
            Log.i("PERMISSION", "请求权限成功");
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PermissionUtils.REQUEST_CODE) {
            for (int grantResult : grantResults) {
                if (grantResult != PackageManager.PERMISSION_GRANTED) {
                    Log.e("Permission", "授权失败！");
                    Toast.makeText(this, "获取权限失败, 无法上传图片", Toast.LENGTH_LONG).show();
                    return;
                }
            }
        }
    }

    public void loadingShow() {
        loadingDialog = new Dialog(this, R.style.normal_dialog_style);
        View loadingView = View.inflate(this, R.layout.dialog_loading, null);
        loadingDialog.setContentView(loadingView);
        //使得点击对话框外部不消失对话框
        loadingDialog.setCanceledOnTouchOutside(false);
        AVLoadingIndicatorView avi = loadingView.findViewById(R.id.avi);
        avi.show();
        loadingDialog.show();
    }
}